<?php
class Db_Mysql_Table extends Db_Sql_Table
{
    const PARSE_FIELD_IDENTIFIER_REGEXP = '/^([\'"`]?)([^\/\\\.]+)(\1)(?:|\.([\'"`]?)([^\/\\\.]+)(\4))$/';

    public function __construct($table)
    {
        if (is_array($table))
        {
            if (empty($table))
            {
                Application::throwException('Array must have ordinary length.');
            }

            if (1 != count($table))
            {
                Application::throwException('Array must have ordinary length.');
            }

            list ($this->alias, $table) = each($table);
            $this->alias = (0 === $this->alias) ? null : $this->alias;
        }

        if (!preg_match(self::PARSE_FIELD_IDENTIFIER_REGEXP, $table, $matches))
        {
            Application::throwException('Table identifier is incorrect!');
        }

        if (mb_strlen($matches[2]) && isset($matches[5]) && mb_strlen($matches[5]))
        {
            $this
                ->setDb($matches[2])
                ->setTable($matches[5]);
        }
        elseif (mb_strlen($matches[2]))
        {
            $this->setTable($matches[2]);
        }
    }

    public function __toString()
    {
        return (mb_strlen($this->getDb()) ? $this->db()->quoteDb($this->getDb()) . '.' : '') //DB
                .  $this->db()->quoteTable($this->getTable()) // TABLE
                . (mb_strlen($this->getAlias()) ? ' AS ' . $this->db()->quoteAlias($this->getAlias()) : ''); //ALIAS
    }
}
?>
